<template>
  <div class="ai-chat-container">
    <div class="ai-chat-header">
      <h3>AI 智能助手</h3>
    </div>

    <div class="ai-chat-messages" ref="messagesContainer">
      <div v-if="messages.length === 0" class="ai-chat-empty">
        <p>开始与AI助手对话吧！</p>
      </div>
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="[
          'ai-chat-message',
          message.role === 'user' ? 'user-message' : 'assistant-message',
        ]"
      >
        <div class="message-content">{{ message.content }}</div>
      </div>
      <div v-if="loading" class="ai-chat-message assistant-message">
        <div class="message-content loading">AI正在思考中...</div>
      </div>
    </div>

    <div class="ai-chat-input">
      <input
        v-model="userInput"
        @keyup.enter="sendMessage"
        placeholder="输入您的问题..."
        :disabled="loading || !apiKeySet"
      />
      <button
        @click="sendMessage"
        :disabled="loading || !userInput || !apiKeySet"
      >
        发送
      </button>
    </div>

    <div class="ai-chat-settings" v-if="!apiKeySet">
      <div class="api-key-warning">
        <span>请在环境变量中设置有效的API密钥</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from "vue";
import { useAiApi } from "../services/aiApi";

interface ChatMessage {
  role: "user" | "assistant";
  content: string;
}

const { sendChatMessage, checkApiKey, getApiKey } = useAiApi();

// 状态变量
const userInput = ref("");
const messages = ref<ChatMessage[]>([]);
const loading = ref(false);
const messagesContainer = ref<HTMLElement | null>(null);
const apiKeySet = ref(false);

// 检查环境变量中是否有API密钥
onMounted(async () => {
  try {
    // 验证环境变量中的API密钥是否有效
    const isValid = await checkApiKey();
    if (isValid) {
      apiKeySet.value = true;
      // 添加欢迎消息
      messages.value.push({
        role: "assistant",
        content: "你好！我是AI助手，有什么可以帮助你的吗？",
      });
    } else {
      console.error("环境变量中的API密钥无效");
    }
  } catch (error) {
    console.error("验证API密钥时出错:", error);
  }
});

// 发送消息
const sendMessage = async () => {
  if (!userInput.value || loading.value || !apiKeySet.value) return;

  // 添加用户消息
  const userMessage = userInput.value.trim();
  messages.value.push({
    role: "user",
    content: userMessage,
  });
  userInput.value = "";
  loading.value = true;

  // 滚动到底部
  await nextTick();
  scrollToBottom();

  try {
    // 发送消息到AI API（支持流式响应）
    let assistantMessage = {
      role: "assistant",
      content: "",
    };
    messages.value.push(assistantMessage);

    const response = await sendChatMessage(userMessage, (chunk) => {
      // 逐步更新AI回复
      assistantMessage.content += chunk;
      messages.value = [...messages.value];

      // 滚动到底部
      scrollToBottom();
    });
  } catch (error) {
    console.error("发送消息时出错:", error);
    messages.value.push({
      role: "assistant",
      content: "抱歉，处理您的请求时出错。请稍后重试。",
    });
  } finally {
    loading.value = false;
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom();
  });
});
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  margin: 0 auto;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.ai-chat-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #f5f7fa;
  border-radius: 8px 8px 0 0;
}

.ai-chat-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.ai-chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.ai-chat-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
}

.ai-chat-message {
  margin-bottom: 12px;
  max-width: 80%;
  word-break: break-word;
}

.user-message {
  margin-left: auto;
}

.assistant-message {
  margin-right: auto;
}

.message-content {
  padding: 10px 14px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.5;
}

.user-message .message-content {
  background-color: #409eff;
  color: white;
  border-bottom-right-radius: 4px;
}

.assistant-message .message-content {
  background-color: #e9ecef;
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-content.loading {
  opacity: 0.7;
}

.ai-chat-input {
  display: flex;
  padding: 12px 16px;
  border-top: 1px solid #e8e8e8;
}

.ai-chat-input input {
  flex: 1;
  padding: 10px 14px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  font-size: 14px;
}

.ai-chat-input input:focus {
  border-color: #409eff;
}

.ai-chat-input button {
  margin-left: 10px;
  padding: 0 15px;
  height: 40px;
  border: none;
  border-radius: 4px;
  background-color: #409eff;
  color: white;
  font-size: 14px;
  cursor: pointer;
}

.ai-chat-input button:hover {
  background-color: #66b1ff;
}

.ai-chat-input button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.ai-chat-settings {
  padding: 12px 16px;
  border-top: 1px solid #e8e8e8;
  background-color: #f5f7fa;
  border-radius: 0 0 8px 8px;
}

.api-key-input {
  display: flex;
}

.api-key-input input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  font-size: 14px;
}

.api-key-input button {
  margin-left: 10px;
  padding: 0 15px;
  height: 36px;
  border: none;
  border-radius: 4px;
  background-color: #67c23a;
  color: white;
  font-size: 14px;
  cursor: pointer;
}

.api-key-set {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reset-button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  background-color: #f56c6c;
  color: white;
  font-size: 12px;
  cursor: pointer;
}

.api-key-warning {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #f56c6c;
  font-size: 14px;
  padding: 8px 0;
}
</style>
